// pages/tool/card/make1/print/print.js
const app = getApp();
app.func.page({

    /**
     * 页面的初始数据
     */
    data: {
        hideprice: true,
        cardNum: 0,
        printPrice: 0,
        popUp: false,
        progress: [2, 2, 2, 1,],
        printType: [{name: '纸质印刷'}, {name: '电子券'}],
        printNum: '',
        currentType: 0,
        currentnum: 99,
        makeNum: '',
        time: {type: "date", field: "delivery", format: "yyyy-MM-dd"},
        region: ['请选择', '请选择', '请选择'],


        shareimg: {
            name: "",
            field: "https://files.dianlinet.com/dianli/images/2020-03-02/15-29-44.jpg",
            tips: "默认为系统封面图，如有需要，您可以重新上传封面图片,尺寸643*513px",
            type: "pic",
            src: ''
        },
        popup: false,
        tiptext:'',
        auth_url:'',
        showtips:false,
        tipsData:{},
        invoiceInfo:{
            finance_company:'',
            finance_taxno:'',
            finance_name:'',
            finance_tel:'',
            finance_address:'',
            finance_content:'',
        }
    },

    showBox: function () {
        // console.log('打开弹框');
        this.setData({popUp: true});
    },
    cancel: function () {
        this.setData({popUp: false});
    },

    choonseType: function (e) {
        let index = e.currentTarget.dataset.index;
        this.setData({currentType: index});
    },


    printFare: function (num) {
        let prices = this.data.prices;
        let printPrice;
        for (let i = prices.length - 1; i >= 0; i--) {
            if (num >= prices[i].mincount) {
                printPrice = prices[i].price;
                break;
            }
        }
        let printSumPrice = num * printPrice;
        this.setData({
            hideprice: false,
            cardNum: num,
            printPrice: printPrice,
            printSumPrice: printSumPrice
        });
    },

    //制卡数量
    choonsenum: function (e) {
        let index = e.currentTarget.dataset.index;
        this.setData({currentnum: index, makeNum: ''}, () => {
            let num = this.data.printNum[index];
            this.printFare(num);
        });
    },
    inputnum: function (e) {
        console.log(e);
        let value = e.detail.value;
        this.setData({currentnum: 99, makeNum: value}, () => {
            this.printFare(value);
        });
    },


    //兑换有效期改变
    onFieldChange: function (e) {
        console.log(e);
        var field = e.currentTarget.dataset.field;
        var value = e.detail.value;
        var _v = e.detail._v;
        this.setData({
            ["time." + field]: value,
            ["time." + field + "_v"]: _v
        });
    },

    //微信分享图改变
    onShareImgChange: function (e) {
        console.log(e);
        let value = e.detail.value;
        this.setData({
            ["shareimg.src"]: value
        });
    },


    //更新选择的地址
    bindRegionChange: function (e) {
        this.setData({
            region: e.detail.value,
            provinceName: e.detail.value[0]
        });
    },

    formsubmit: function (e) {
        let name = e.detail.value.name;
        let telNumber = e.detail.value.telNumber;
        let address = e.detail.value.address;
        let content = e.detail.value.content;

        let data = this.data;
        let region = data.region;
        let provinceName = data.region[0];
        let cityName = data.region[1];
        let countyName = data.region[2];
        if (data.makeNum.length == 0 && data.currentnum == 99) {
            app.func.toastPromise("制卡数量不能为空")
            return;
        }
        if (telNumber == "") {
            app.func.toastPromise('手机号不能为空')
            return;
        }

        if (this.data.currentType == 0) {
            if (data.currentnum == 99) {
                let makeNum = parseInt(data.makeNum);
                if (makeNum < this.data.mincount || makeNum % this.data.mincount != 0) {
                    app.func.toastPromise("制卡数量须是" + this.data.mincount + "的整数倍");
                    return;
                }
            }
            if (!data.time['delivery_v']) {
                app.func.toastPromise('请填写送达日期')
                return;
            }
            if (name == "") {
                app.func.toastPromise('姓名不能为空')
                return;
            }
            if (region == "" || provinceName == "请选择") {
                app.func.toastPromise('省级区域不能为空')
                return;
            }
            if (region == "" || cityName == "请选择") {
                app.func.toastPromise('市级区域不能为空')
                return;
            }
            if (region == "" || countyName == "请选择") {
                app.func.toastPromise('县级区域不能为空')
                return;
            }
            if (address == "") {
                app.func.toastPromise('详细地址不能为空')
                return;
            } else {
                let json = {
                    id: data.printid,
                    num: data.makeNum.length == 0 ? data.printNum[data.currentnum] : data.makeNum,
                    time: data.time['delivery_v'],
                    name: name,
                    mobile: telNumber,
                    address: region + address,
                    content: content
                };
                this.makecard(json);
            }
        } else {
            let json = {
                id: data.printid,
                num: data.makeNum.length == 0 ? data.printNum[data.currentnum] : data.makeNum,
                mobile: telNumber,
                content: content,
                share_cover: data.shareimg.src
            };
            let status = e.detail.target.dataset.status;
            if (status == 1) {
                this.showBox();
            } else {
                this.distribute(json);
            }
        }
    },

    mergeJson(data1,data2){
        return JSON.parse((JSON.stringify(data1) + JSON.stringify(data2)).replace(/}{/, ','));
    },

    //纸质印刷
    makecard: function (value) {
        let data = this.mergeJson(value,this.data.invoiceInfo);
        app.func.loading('加载中');
        app.func.postPromise('/cardmake/makecard', data)
            .then(([code, res]) => {
                wx.hideLoading();
                if (code == 200) {
                    return this.payPrint(res.data.id, res.data.deal);
                } else if (code == 6001) {
                    app.func.confirm('额度超限',res.message)
                        .then(()=>{
                            wx.navigateTo({
                                url: '/pages/about/balance/chargelist/addcharge/addcharge?price=2000'
                            })
                        })
                } else {
                    return app.func.toastPromise(res.message)
                }
            }).finally(()=>{
                wx.hideLoading();
        })
    },

    payPrint: function (makeid, deal) {
        var paymentid = null;
        var checkstatus = function (status) {
            if (status == 2) {
                return status;
            }
            return app.func.toastPromise('支付成功')
                .then(() => {
                    return app.func.getPromise('/card/papercarddetail/' + makeid)
                        .then(([code, res]) => {
                            return res.data.cardmakestatus;
                        }, app.func.reject);
                });
        };
        app.func.postPromise('/v2/makecard/pay/' + makeid, {})
            .then(([code, res]) => {
                if (code == 200) {
                    var param = res.data;
                    paymentid = res.data.paymentid;

                    return app.func.promise((resolve, reject) => {
                        wx.requestPayment({
                            timeStamp: param.timeStamp,
                            nonceStr: param.nonceStr,
                            package: param.package,
                            signType: param.signType,
                            paySign: param.paySign,
                            success(res) {
                                resolve(0);
                            },
                            fail(res) {
                                return app.func.postPromise("/v2/pay/unpay/" + paymentid, {})
                                    .then(reject);
                            }
                        });
                    });
                } else {
                    return app.func.reject();
                }
            }).then(checkstatus).then(checkstatus).then(checkstatus)
            .then((status) => {
                if (status == 2) {
                    wx.redirectTo({
                        url: '/tools/pages/tool/card/make1/print/index/index?index=0&id=' + makeid
                    });
                }
            }).finally(() => {
            this.setData({processing: false});
        });
    },

    //电子券
    distribute: function (data) {
        app.func.execute(()=>{
            return app.func.postPromise('/cardmake/distribute', data)
                .then(([code, res]) => {
                    if (code == 200) {
                        wx.redirectTo({
                            url: '/tools/pages/tool/card/make1/print/index/index?index=1&id=' + res.data
                        })
                    } else if (code == 6001) {
                        wx.hideLoading();
                        this.setData({
                            showtips:true,
                            tipsData:{
                                title:'额度超限',
                                content:res.message,
                                sure:{name:"联系客服",url:"button"},
                                cancel:{name:"关闭",url:"close"},
                            }
                        });
                    } else {
                        return app.func.toastPromise(res.message)
                    }
                })
        });
    },


    myinfo: function (cd) {
        app.func.getPromise('/my/info')
            .then(([code, res]) => {
                cd(code, res);
            })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.myinfo((code, res) => {
            if (res.data.customers[0].status != 3 || res.data.customers[0].card_audit != 3) {
                this.setData({
                    popup: true,
                    page_url:'print',
                    tiptext:res.data.customers[0].print_alert,
                    auth_url:res.data.customers[0]. auth_url
                });
                return;
            }
        });

        this.setData({
            printid: options.printid,
            skip: options.skip
        }, () => {
            this.carmakenumber(options.printid);
        });
    },

    carmakenumber: function (id) {
        app.func.postPromise('/cardtype/printfare/' + id)
            .then(([code, res]) => {
                this.setData({
                    printInfo: res.data.content,
                    printNum: res.data.choice, mincount: res.data.mincount, prices: res.data.prices
                });
            }).then(() => {
            app.func.getPromise('/cardtype/cardtypepic/' + id)
                .then(([code, res]) => {
                    this.setData({cardimg: res.data});
                })
        })
    },


    skip: function () {
        wx.switchTab({
            url: '/tools/pages/tool/card/index/index'
        })
    },

    makeinvoice() {
        let that = this;
        let result = that.data.invoiceInfo.finance_company.length;
        let param1,param2;
        if(result > 0){
            param1 = `/pages/about/card/print/makeinvoice/makeinvoice?price=${this.data.printSumPrice}&existinfo=true`;
            param2 = this.data.invoiceInfo;
        }else{
            param1 = `/pages/about/card/print/makeinvoice/makeinvoice?price=${this.data.printSumPrice}`;
            param2 = '';
        }
        this.navigateModal(param1,param2)
            .then((res) => {
                that.setData({invoiceInfo: res});
            }).catch((res) => {
            console.log(res);
        });
    }

})
